package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"hospital-sys/models"
)

type DoctorControllers struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *DoctorControllers) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "获取文件失败",
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "图片不能超过2MB",
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传文件失败",
		}
		c.ServeJSON()
		return
	} else {
		Url := "http://127.0.0.1:8080/" + path
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传文件成功",
			Data: Url,
		}
		c.ServeJSON()
	}

}

func (c *DoctorControllers) Add() {
	name := c.GetString("name")
	phone := c.GetString("phone")
	address := c.GetString("address")
	asc := c.GetString("asc")
	names := c.GetString("names")
	img := c.GetString("img")
	doctor := models.Doctor{
		Name:    name,
		Phone:   phone,
		Address: address,
		Asc:     asc,
		Names:   names,
		Img:     img,
	}
	err := models.DB.Create(&doctor).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
		}
		c.ServeJSON()
	}
}

func (c *DoctorControllers) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	offset := (page - 1) * size
	var count int64
	query := models.DB.Model(&models.Doctor{})
	var doctor []models.Doctor
	query.Count(&count)
	query.Offset(offset).Limit(size).Find(&doctor)
	fxd := make(map[string]interface{})
	fxd["count"] = count
	fxd["doctor"] = doctor
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "分页查询成功",
		Data: fxd,
	}
	c.ServeJSON()
	return
}

func (c *DoctorControllers) Del() {
	id, _ := c.GetInt("id")
	var doctor []models.Doctor
	err := models.DB.Delete(&doctor, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
		}
		c.ServeJSON()
	}
}

func (c *DoctorControllers) Show() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	phone := c.GetString("phone")
	address := c.GetString("address")
	asc := c.GetString("asc")
	names := c.GetString("names")
	img := c.GetString("img")
	doctor := models.Doctor{
		Name:    name,
		Phone:   phone,
		Address: address,
		Asc:     asc,
		Names:   names,
		Img:     img,
	}
	err := models.DB.Where("id=?", id).Updates(&doctor).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
		}
		c.ServeJSON()
	}
}
